const async = require('async');

const pageQuery = function ({page, pageSize, Model, populate, queryParams = {}, queryKey = '', sortParams, callback}) {
    return new Promise(function(resolve, reject){
        const start = (page - 1) * pageSize;
        const pageData = {
            page: page,
            pageSize: pageSize
        };
        async.parallel({
            count: function (done) {  // 查询数量
                Model.countDocuments(queryParams).exec(function (err, count) {
                    done(err, count);
                });
            },
            records: function (done) {   // 查询一页的记录
                console.log(queryParams);
                
                const queryModel = Model.find(queryParams, queryKey).skip(start).limit(pageSize).sort({'_id': -1})
                queryModel.exec((err, doc) => {
                    done(err, doc);
                })
                
            }
        }, function (err, results) {
            if(err) reject(err)
            let count = results.count;
            pageData.pageCount = parseInt(count / pageSize + 1)
            pageData.results = results.records
            pageData.total = count
            resolve(pageData)
        });
    })
    
};

module.exports = pageQuery
